package com.rising.face.ali.bishi.threadprint2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: rising
 * @Description:
 * 顺序递增打印正整数，从1开始打印到100，中间换行分隔。不允许重复打印出相同的数字，比如打印结果里出现2个5，3个6之类的。
 * 要求如下：
 * 1、使用三个线程A、B、C，其中线程A打印3的倍数，B打印5的倍数，C打印其他数字。
 * @Date: create in 2021/2/6 22:01
 */
public class ThreadPrint2bian implements Runnable{

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    private int finalNum;

    public ThreadPrint2bian(int finalNum) {
        this.finalNum = finalNum;
    }

    //遍历总数
    private volatile int count = 1;

    private String threadName(int element) {
        if (element % 5 == 0) {
            return "B";
        } else if (element % 3 == 0) {
            return "A";
        } else {
            return "C";
        }
    }

    public void print() {
        lock.lock();
        try {
            //数组遍历完则结束
            while (count < finalNum) {
                //当前线程名字不匹配，则阻塞
                while (!Thread.currentThread().getName().equals(threadName(count))) {
                    condition.await();
                }
                if (count > finalNum) {
                    break;
                }
                //执行打印
                System.out.println("线程" + Thread.currentThread().getName() + "打印：" +count);
                count++;
                condition.signalAll();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ThreadPrint2bian data = new ThreadPrint2bian(100);
        new Thread(data, "C").start();
        new Thread(data, "B").start();
        new Thread(data, "A").start();
    }

    @Override
    public void run() {
        print();
    }
}
